package com.ting.etp.host.starter;

import com.ting.etp.loader.jar.JarFile;
import com.ting.etp.loader.start.EtpStart;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.concurrent.CountDownLatch;

/**
 * @author zifang
 */
@Slf4j
public class EtpApplicationStart {

    private static EtpStart etpStart;
    private static String[] args;

    private static final CountDownLatch COUNT_DOWN_LATCH = new CountDownLatch(1);

    public static void launch(Class<? extends EtpStart> etpStart, String[] args) throws Exception{
        Objects.requireNonNull(etpStart, "etpStart 不能为空");
        log.info("EtpStartLoader launch...");
        EtpStart start = etpStart.getConstructor().newInstance();
        EtpApplicationStart.etpStart = start;
        EtpApplicationStart.args = args;
        launch(args);
    }

    private static void launch(String[] args) {
        etpStart.developmentMode();
        JarFile.registerUrlProtocolHandler();
        Thread launchThread = new Thread(new Runner(etpStart,args));
        launchThread.start();
        try {
            COUNT_DOWN_LATCH.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static class Runner implements Runnable{

//        private final EtpStart etpStart;
//        private final String[] args;

        public Runner(EtpStart etpStart,String[] args) {
//            this.etpStart = etpStart;
//            this.args = args;
        }

        @Override
        public void run() {
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            try {
                Thread thread = Thread.currentThread();
                ClassLoader oldClassLoader  = thread.getContextClassLoader();
                try {
                    thread.setContextClassLoader(classLoader);
                    etpStart.run(args);
                } finally {
                    thread.setContextClassLoader(oldClassLoader);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                COUNT_DOWN_LATCH.countDown();
            }
        }
    }

//    private static void main(String[] args) throws Exception {
//        Objects.requireNonNull(etpStart, "etpStart 不能为空");
//        EtpLauncher<ClassLoader> launcher = new EtpDevLauncher(etpStart);
//        launcher.run(args);
//    }

}
